//
//  TaskView.swift
//  TanTan_Kotlin
//
//  Created by EDY on 5/26/25.
//

import SwiftUI


class Task: Identifiable,ObservableObject {
    let id = UUID()     //唯一标识
    @Published var title: String
    @Published var isCompleted: Bool
    
    init(title: String, isCompleted: Bool = false) {
        self.title = title
        self.isCompleted = isCompleted
    }
    
}

class TaskManager: ObservableObject {
    @Published var tasks: [Task] = []
    func addTask(title: String) {
        let newTask = Task(title: title)
        tasks.append(newTask)
    }
    
    func removeTask(at offsets: IndexSet) {
        tasks.remove(atOffsets: offsets)
    }
}

struct TaskView: View {
    @StateObject private var taskManager = TaskManager()
    @State private var newTaskTitle = ""
    
    var body: some View {
        NavigationView{
            VStack {
                HStack {
                    TextField("输入任务", text: $newTaskTitle)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    Button(action: {
                        if !newTaskTitle.isEmpty {
                            taskManager.addTask(title: newTaskTitle)
                            newTaskTitle = ""
                        }
                    }){
                        Text("添加")
                            .padding()
                            .background(Color.blue)
                            .foregroundColor(.white)
                            .cornerRadius(10)
                    }
                }.padding()
                List {
                    ForEach(taskManager.tasks) { task in
                        TaskRow(task: task)
                    }.onDelete(perform: taskManager.removeTask)
                }
                .navigationTitle("任务管理器")
            }
        }
    }
}
    
    struct TaskRow: View {
        @ObservedObject var task: Task
        var body: some View {
            HStack {
                Text(task.title)
                Spacer()
                if task.isCompleted {
                    Image(systemName: "checkmark.circle.fill")
                        .foregroundColor(.green)
                } else {
                    Image(systemName: "circle")
                        .foregroundColor(.gray)
                }
            }
            .contentShape(Rectangle())
            .onTapGesture {
                task.isCompleted.toggle()
            }
        }
    }



#Preview {
    TaskView()
}
